package com.zeei.lcp.service.imp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.zeei.lcp.dao.QRcodeLcpDao;
import com.zeei.lcp.service.QRcodeLcpService;
import com.zeei.lcp.vo.TreeNodeLcpVO;

/**
 * @类型名称：QRcodeLcpServiceImpl
 * @类型描述：二维码管理Service
 * @功能描述：生命周期---二维码管理
 * @创建作者：meng.jy
 * @创建时间: 2018年1月21日
 */
@Service("QRcodeLcpServiceImpl")
public class QRcodeLcpServiceImpl implements QRcodeLcpService {

	@Autowired
	private QRcodeLcpDao qrcodeLcpDao;

	@Override
	public List<TreeNodeLcpVO> queryTreeList(TreeNodeLcpVO vo) {

		Assert.notNull(vo, "入参对象不能为空");
		Assert.notNull(vo.getLevel(), "行政等级不能为空");

		List<TreeNodeLcpVO> areaList = this.qrcodeLcpDao.queryAreaTree();// 数据库查询
		List<TreeNodeLcpVO> retList = new ArrayList<TreeNodeLcpVO>();// 返回封装
		Map<String, TreeNodeLcpVO> treemap = new HashMap<String, TreeNodeLcpVO>();// 当作索引使用
		Map<String, TreeNodeLcpVO> treemapTmp = new HashMap<String, TreeNodeLcpVO>();// 没有处理父节点的记录
		for (TreeNodeLcpVO areavo : areaList) {
			//
			TreeNodeLcpVO treeTmp = null;
			if (treemap.get(areavo.getRegionCode()) != null) {
				treeTmp = treemap.get(areavo.getRegionCode());
			} else {
				treeTmp = areavo;
				treemap.put(treeTmp.getRegionCode(), treeTmp);
			}
			// 父节点处理
			if (treemap.get(treeTmp.getpCode()) != null) {
				TreeNodeLcpVO ptreeTmp = treemap.get(treeTmp.getpCode());
				ptreeTmp.getChildren().add(treeTmp);
			} else if (!treeTmp.getLevel().equals(vo.getLevel())) {
				treemapTmp.put(treeTmp.getRegionCode(), treeTmp);
			}
			//
			if (treeTmp.getLevel().equals(vo.getLevel())) {
				retList.add(treeTmp);
			}
		}
		//
		if (treemapTmp != null && !treemapTmp.isEmpty() && treemapTmp.size() > 0) {
			for (Iterator<Map.Entry<String, TreeNodeLcpVO>> it = treemapTmp.entrySet().iterator(); it.hasNext();) {
				Map.Entry<String, TreeNodeLcpVO> entry = it.next();
				TreeNodeLcpVO treeTmp = entry.getValue();
				if (treemap.get(treeTmp.getpCode()) != null) {
					TreeNodeLcpVO ptreeTmp = treemap.get(treeTmp.getpCode());
					ptreeTmp.getChildren().add(treeTmp);
				}
			}
		}
		treemapTmp.clear();
		//
		List<TreeNodeLcpVO> enterList = this.qrcodeLcpDao.queryEnterpriseList();
		for (TreeNodeLcpVO entervo : enterList) {
			if (treemap.get(entervo.getpCode()) != null) {
				treemap.get(entervo.getpCode()).getChildren().add(entervo);
			}
		}
		treemap.clear();

		return retList;

	}

	@Override
	public List<TreeNodeLcpVO> queryDischargePoints(TreeNodeLcpVO vo) {

		Assert.notNull(vo, "入参对象不能为空");
		Assert.hasText(vo.getPsCode(), "污染源代码不能为空");

		return this.qrcodeLcpDao.queryDischargePoints(vo);
	}

}
